import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class test1 {
    public static void main(String[] args) {

    }
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }
    public int maxSubArray(int[] nums) {
        int pre = 0, maxAns = nums[0];
        for (int x : nums) {
            pre = Math.max(pre + x, x);
            maxAns = Math.max(maxAns, pre);
        }
        return maxAns;
    }
    public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    public ListNode swapPairs(ListNode head) {
        ListNode pHead=new ListNode(-1);
        pHead.next=head;
        ListNode cur=pHead;
        while(cur.next!=null&&cur.next.next!=null){
            ListNode temp=cur.next;
            ListNode temp1=cur.next.next.next;
            cur.next=cur.next.next;
            cur.next.next=temp;
            temp.next=temp1;
            cur=cur.next.next;
        }
        return pHead.next;
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pHead=new ListNode(0);
        pHead.next=head;
        ListNode f=pHead;
        ListNode s=pHead;
        for(int i=0;i<n;i++){
            f=f.next;
        }
        while(f.next!=null){
            f=f.next;
            s=s.next;
        }
        s.next=s.next.next;
        return pHead.next;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;
        int lenA = 0, lenB = 0;
        while (curA != null) {
            lenA++;
            curA = curA.next;
        }
        while (curB != null) {
            lenB++;
            curB = curB.next;
        }
        curA = headA;
        curB = headB;
        if (lenB > lenA) {
            int tmpLen = lenA;
            lenA = lenB;
            lenB = tmpLen;
            ListNode tmpNode = curA;
            curA = curB;
            curB = tmpNode;
        }
        int gap = lenA - lenB;
        while (gap-- > 0) {
            curA = curA.next;
        }
        while (curA != null) {
            if (curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
    public ListNode detectCycle(ListNode head) {
        ListNode pos=head;
        Set<ListNode> visited = new HashSet<ListNode>();
        while(pos!=null){
            if(visited.contains(pos)){
                return pos;
            }else{
                visited.add(pos);
            }pos = pos.next;
        }return null;
    }

}

